from rest_framework import serializers
from ..models.Institution import Institution
from ..serializers.departListSerializer import DepListSerializer

class InstCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Institution
        fields = ["name", "zh_name", "ins_code", "country", "city", "address", "postal_code", "contact_number", "email", \
                  "website", "founded_date", "description", "inst_type"]
    
    def create(self, validated_data):
        i = Institution.objects.create(**validated_data)

        return i

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance
    
    
class InstInfoSerializer(serializers.ModelSerializer):
    departments = serializers.SerializerMethodField()
    
    class Meta:
        model = Institution
        fields = ["uuid", "name", "zh_name", "ins_code", "country", "city", "address", "postal_code", "contact_number", "email", \
                  "website", "founded_date", "description", "inst_type", 'departments']
        
    def get_departments(self, obj):
        department_list = []
        for department in obj.department_set.all():
            dep_data = DepListSerializer(department).data
            dep_data['dep_type'] = department.dep_type.uuid
            department_list.append(dep_data)
        return department_list